package com.inifitness.admin.core.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inifitness.admin.core.system.converter.EventParamConvert;
import com.inifitness.admin.core.system.mapper.SysEventParamMapper;
import com.inifitness.admin.core.system.model.entity.SysEventParam;
import com.inifitness.admin.core.system.model.form.EventParamForm;
import com.inifitness.admin.core.system.model.query.EventParamPageQuery;
import com.inifitness.admin.core.system.model.vo.EventParamPageVO;
import com.inifitness.admin.core.system.service.SysEventParamService;
import com.inifitness.common.model.Option;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * 系统管理-事件参数服务实现类
 *
 * @author
 * @since 2024-05-31 13:46:16
 */

@Service
@RequiredArgsConstructor
@Log4j2
public class SysEventParamServiceImpl extends
    ServiceImpl<SysEventParamMapper, SysEventParam> implements SysEventParamService {

  private final EventParamConvert eventParamConvert;
  private final ApplicationEventPublisher publisher;

  @Override
  public Page<EventParamPageVO> getEventParamPage(EventParamPageQuery queryParams) {
    // 查询参数
    int pageNum = queryParams.getPageNum();
    int pageSize = queryParams.getPageSize();
    String keywords = queryParams.getKeywords();
    String eventCode = queryParams.getEventCode();

    // 查询数据
    Page<SysEventParam> page = this.page(
        new Page<>(pageNum, pageSize),
        new LambdaQueryWrapper<SysEventParam>()
            .eq(SysEventParam::getEventCode, eventCode)
            .and(CharSequenceUtil.isNotBlank(keywords),
                w -> w.like(SysEventParam::getLabel, keywords)
                    .or()
                    .like(SysEventParam::getCode, keywords)
            )
            .select(
                SysEventParam::getId,
                SysEventParam::getEventCode,
                SysEventParam::getLabel,
                SysEventParam::getCode,
                SysEventParam::getSort,
                SysEventParam::getStatus,
                SysEventParam::getDeleted,
                SysEventParam::getRemark,
                SysEventParam::getCreateTime,
                SysEventParam::getCreateBy,
                SysEventParam::getUpdateTime,
                SysEventParam::getUpdateBy
            )
    );

    Page<EventParamPageVO> pageResult = eventParamConvert.entity2Page(page);
    return pageResult;
  }

  @Override
  public EventParamForm getEventParamForm(Long id) {
    // 获取entity
    SysEventParam entity = this.getOne(new LambdaQueryWrapper<SysEventParam>()
        .eq(SysEventParam::getId, id)
        .select(
            SysEventParam::getId,
            SysEventParam::getEventCode,
            SysEventParam::getLabel,
            SysEventParam::getCode,
            SysEventParam::getSort,
            SysEventParam::getStatus,
            SysEventParam::getDeleted,
            SysEventParam::getRemark,
            SysEventParam::getCreateTime,
            SysEventParam::getCreateBy,
            SysEventParam::getUpdateTime,
            SysEventParam::getUpdateBy
        ));
    Assert.isTrue(entity != null, "对象不存在");

    // 实体转换
    EventParamForm form = eventParamConvert.entity2Form(entity);
    return form;
  }

  @Override
  public boolean saveEventParam(EventParamForm form) {
    boolean exist = this.count(new LambdaQueryWrapper<SysEventParam>()
        .eq(SysEventParam::getEventCode, form.getEventCode())
        .and(w -> w.eq(SysEventParam::getCode, form.getCode())
            .or().eq(SysEventParam::getLabel, form.getLabel()))) > 0;
    Assert.isTrue(!exist, "参数名称或占位符已存在");

    // 实体对象转换 form->entity
    SysEventParam entity = eventParamConvert.form2Entity(form);
    // 持久化
    boolean result = this.save(entity);
    return result;
  }

  @Override
  public boolean updateEventParam(Long id, EventParamForm form) {
    boolean exist = this.count(new LambdaQueryWrapper<SysEventParam>()
        .eq(SysEventParam::getEventCode, form.getEventCode())
        .and(w -> w.eq(SysEventParam::getCode, form.getCode())
            .or().eq(SysEventParam::getLabel, form.getLabel()))
        .ne(SysEventParam::getId, id)) > 0;
    Assert.isTrue(!exist, "参数名称或占位符已存在");
    // 获取对象
    SysEventParam entity = eventParamConvert.form2Entity(form);
    boolean result = this.updateById(entity);
    return result;
  }

  @Override
  public boolean deleteEventParams(String ids) {
    Assert.isTrue(CharSequenceUtil.isNotBlank(ids), "删除数据为空");
    List<String> idList = new ArrayList<>(Arrays.asList(ids.split(",")));
    //TODO:(2024-06-24 SJF) 删除时，需要好处理已经使用该字段的模板
    // 删除对象
    boolean result = this.removeByIds(idList);
    return result;
  }


  /**
   * 获取下拉列表
   *
   * @return
   */
  @Override
  public List<Option<Long>> listEventParamOptions(String eventCode) {
    // 数据库数据
    List<SysEventParam> list = this.list(new LambdaQueryWrapper<SysEventParam>()
        .eq(SysEventParam::getEventCode, eventCode)
        .select(SysEventParam::getId, SysEventParam::getLabel)
    );

    // 转换下拉数据
    List<Option<Long>> options = CollUtil.emptyIfNull(list)
        .stream()
        .map(item -> new Option<Long>(item.getId(), item.getLabel()))
        .toList();
    return options;
  }
}
